const app = getApp()
const util = require('../../utils/util.js');
const WxParse = require('../../wxParse/wxParse.js');
const api = require('../../utils/api.js');
//客户已经选中的分类id的数组
var specArr = [];
//客户已经选中的分类名称的数组
var specArrText = [];
Page({
    data: {
        storageDataArrLength:0,
        goodCount: 1,
        hasMask: 0,
        selectSKUDetailId: -1,
        selectSKU2DetailId: -1,
        sku1: null,
        sku2: null,
        skuInfo: {},
        goodDetail: {},
        //页面颜色
        pageColor: app.pageColor,
        //轮播图配置
        bannerConfiguration: app.bannerConfiguration
    },
    //是否选择了sku
    isSelectSku: function () {
        var sku = this.data.goodDetail.sku
        if (specArr.length < sku.length) {
            return false;
        } else if (sku.length != 0 && specArr[0] == undefined) {
            return false;
        }
        return true;

    },

    //是否可以通过sku组合请求数据
    isHttpsBySKU: function () {
        if (this.isSelectSku()) {
            return true;
        }
        return false;
    },
    //减少数量
    subtract: function () {
        if (!this.isSelectSku()) {
            util.failToast("请选择分类")
            return;
        }
        if (this.data.goodCount > 1) {
            this.setData({
                goodCount: this.data.goodCount - 1,
            })
        }

    },
    //增加数量
    add: function () {
        if (!this.isSelectSku()) {
            util.failToast("请选择分类")
            return;
        }
        this.setData({
            goodCount: this.data.goodCount + 1
        })

    },
    //获取中的商品详细信息
    getSelectGoodInfo: function (options) {
        if (this.isSelectSku()) {
            var isSpike = options.currentTarget.dataset.isspike;
            var startAt = "";
            var endAt = "";
            if(isSpike==1){
                startAt = options.currentTarget.dataset.startat;
                endAt = options.currentTarget.dataset.endat;
            }
            var skuName = "";
            for (var i = 0; i < specArrText.length; i++) {
                skuName += specArrText[i] + "/"
            }
            var skuId = "";
            for (var i = 0; i < specArr.length; i++) {
                skuId += specArr[i] + "."
            }
            skuId = skuId.substring(0, skuId.length - 1)
            skuName = skuName.substring(0, skuName.length - 1)
            var goodId = options.currentTarget.dataset.goodid;
            var goodName = options.currentTarget.dataset.goodname;
            var goodSales = options.currentTarget.dataset.goodsales;
            var goodPrice = options.currentTarget.dataset.goodprice;
            var goodOldPrice = options.currentTarget.dataset.goodoldprice;
            var goodDes = options.currentTarget.dataset.gooddes;
            var goodStock = options.currentTarget.dataset.goodstock;
            var goodCover = options.currentTarget.dataset.goodcover;
            var goodCount = this.data.goodCount;
            //存入对象
            var selectGoodInfo = {}
            selectGoodInfo.goodId = goodId;
            if (goodName.length>=25){
                selectGoodInfo.goodName = goodName.substring(0,2525)+"..."
            }else{
                selectGoodInfo.goodName = goodName
            }
            selectGoodInfo.isSpike = isSpike;
            selectGoodInfo.startAt = startAt;
            selectGoodInfo.endAt = endAt;

            selectGoodInfo.goodPrice = goodPrice;
            selectGoodInfo.goodOldPrice = goodOldPrice;
            selectGoodInfo.goodDes = goodDes;
            selectGoodInfo.goodStock = goodStock;
            selectGoodInfo.goodCover = goodCover;
            selectGoodInfo.goodCount = goodCount;
            selectGoodInfo.skuName = skuName;
            selectGoodInfo.goodSales = goodSales;
            selectGoodInfo.skuId = skuId;
            selectGoodInfo.state = 0;
            return selectGoodInfo;
        }
        util.failToast("请选择分类")
    },

    //缓存数据
    cacheData: function (selectGoodInfo){
        //获取购物车本地数据
        var selectGoodInfoArr = []
        var storageDataArr = util.getStorage("selectGoodInfoArr")
        if (storageDataArr == "") {
            selectGoodInfoArr.push(selectGoodInfo);
            util.setStorage("selectGoodInfoArr", selectGoodInfoArr);
            return;
        }
        selectGoodInfoArr = storageDataArr;
        var count =1;
        for (var i = 0; i < selectGoodInfoArr.length;i++){
            if (selectGoodInfo.skuId == selectGoodInfoArr[i].skuId && selectGoodInfo.goodId == selectGoodInfoArr[i].goodId){
                selectGoodInfoArr[i].goodCount +=1 ;
                count = 2;
                break;
            }
        }
        if (count ==1){
            selectGoodInfoArr.push(selectGoodInfo);
            util.setStorage("selectGoodInfoArr", selectGoodInfoArr);
            return;
        }
        util.setStorage("selectGoodInfoArr", selectGoodInfoArr);
        
    },
    
    // 添加购物车
    addCar: function (options) {
        var selectGoodInfo = this.getSelectGoodInfo(options);
        if (selectGoodInfo == undefined) {
            return;
        }
        if (selectGoodInfo.goodStock <= 0) {
            util.failToast("该商品库存不足！")
        }
        util.successToast("加入购物车成功")

        //隐藏弹框
        this.showAndCloseCategory();
        //更新缓存数据
        this.cacheData(selectGoodInfo);
        this.setData({
            storageDataArrLength: this.data.storageDataArrLength+1
        })
    },

    /**
     * 跳转购物车
     */

    toShop:function(){
        wx.switchTab({
            url: '../shop/shop'
        })
    },

    /**
     * 跳转首页
     */

    toHome:function(){
        wx.switchTab({
            url: '../index/index'
        })
    },

    /**
     * 立即购买
     */
    buy: function (options) {
        var spikeState = options.currentTarget.dataset.spikestate;
        
        var goodInfoArr=[]
        var selectGoodInfo = this.getSelectGoodInfo(options);
        if (selectGoodInfo == undefined) {
            return;
        }
        if (selectGoodInfo.goodStock <= 0) {
            util.failToast("库存不足！")
            return;
        }
        if(spikeState==2){
            util.failToast("即将开抢")
            return;
        }
        if(spikeState==3){
            util.failToast("明天再来")
            return;
        }

        goodInfoArr.push(selectGoodInfo);
        this.navigateTo("../firmOrder/firmOrder?goodInfoArr=" + JSON.stringify(goodInfoArr))
        
    },

    /**
     * 页面跳转
     */

    navigateTo: function (url) {
        wx.navigateTo({
            url: url
        })
    },


    //显示和影藏分类弹框
    showAndCloseCategory: function () {
        this.setData({
            hasMask: this.data.hasMask == 0 ? 1 : 0
        })
    },
    //选择第一个分类
    onTapSKU: function (res) {
        var skudetailid = res.currentTarget.dataset.skudetailid;
        var skudetailName = res.currentTarget.dataset.skudetailname;
        specArr[0] = skudetailid;
        specArrText[0] = skudetailName;
        console.log(specArr[0]);
        this.setData({
            selectSKUDetailId: skudetailid
        })
        if (this.isHttpsBySKU()) {
            var skuID = "";
            for (var i = 0; i < specArr.length; i++) {
                skuID += specArr[i] + "."

            }
            console.log("skuID=" + skuID);
            //做数据请求
            this.getGoodDetailInfoBySKU(api.GetSku()+"?sku_id=" + skuID.substring(0, skuID.length - 1))
        }

    },

    //选择第二个分类
    onTapSKU2: function (res) {
        var skudetailid = res.currentTarget.dataset.skudetailid;
        specArr[1] = skudetailid;
        var skudetailName = res.currentTarget.dataset.skudetailname;
        specArrText[1] = skudetailName;
        this.setData({
            selectSKU2DetailId: skudetailid
        })
        if (this.isHttpsBySKU()) {
            //做数据请求
            var skuID = "";
            for (var i = 0; i < specArr.length; i++) {
                skuID += specArr[i] + "."
            }
            //做数据请求
            this.getGoodDetailInfoBySKU(api.GetSku() +"?sku_id=" + skuID.substring(0, skuID.length - 1))

        }
    },

    /**
    * 获取商品详情信息
    */
    getGoodDetail: function (url) {
        util.http(true,"GET", url, '', this.goodDetailCallBack)
    },

    /**
     * 获取详情页回调
     */
    goodDetailCallBack: function (res) {
        var fullCutContents = res.full_cut.length == 0 ? "暂无满减活动" : "";
        for (var i = 0; i < res.full_cut.length; i++) {
            fullCutContents += "满" + res.full_cut[i].price + "减" + res.full_cut[i].cut + ";"
        }
        res.text="立即购买"
        res.state = 0;
        if(res.is_spike==1){
            var myDate = new Date();//获取系统当前时间
            res.currentTimestamp = myDate.getTime();
            //开抢中
            if (res.currentTimestamp >= res.spike_time.start_at * 1000 && 
                res.currentTimestamp <= res.spike_time.end_at * 1000)
            {
                res.text="抢购中"
                res.state = 1;
            } else if (res.currentTimestamp < res.spike_time.start_at * 1000){
                res.text = "即将开抢"
                res.state = 2;
            } else if (res.currentTimestamp > res.spike_time.end_at * 1000){
                res.text = "抢购结束"
                res.state = 3;
            }
            var startAtDate = new Date(res.spike_time.start_at*1000)
            var endAtDate = new Date(res.spike_time.end_at * 1000)
            res.start_at = util.formatTime(startAtDate)
            res.end_at = util.formatTime(endAtDate)
        }

        this.setData({
            fullCutContents:fullCutContents,
            skuInfo: res,
            goodDetail: res
        })
        var sku = res.sku;
        if (res.sku.length == 0) {

        }
        else if (sku.length == 1) {
            var sku1 = sku[sku.length - 1]
            this.setData({
                sku1: sku1
            })
        }
        else if (sku.length == 2) {
            var sku1 = sku[sku.length - 2]
            var sku2 = sku[sku.length - 1]
            this.setData({
                sku1: sku1,
                sku2: sku2
            })
        }
    },

    /**
    * 通过商品规格组合获取商品信息信息
    */
    getGoodDetailInfoBySKU: function (url) {
        util.http(false,"GET", url, '', this.getGoodDetailInfoBySKUCallBack)
    },
    /**
    * 通过商品规格组合获取商品信息信息回调
    */
    getGoodDetailInfoBySKUCallBack: function (res) {
        this.setData({
            skuInfo: res
        })
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        let url = api.goodDetail();
        // WxParse.wxParse('article', 'html', article, this, 5);
        specArr = [];
        specArrText = [];
        var storageDataLength = util.getStorage("selectGoodInfoArr").length;
       
        this.setData({
            storageDataArrLength: storageDataLength
        })
        // 选中的分类数组
        var goodId = options.goodId;
        this.getGoodDetail(url+"?good_id=" + goodId)
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {
        util.setNavigationBarTitle("商品详情页");
    },
})